package service

import (
	"time"

	"agentdesign/models"
)

// ListProjects returns all projects from the database.
func (s *ApiService) ListProjects() ([]models.Project, error) {
	projects := []models.Project{}
	err := s.db.Select(&projects, "SELECT * FROM projects")
	return projects, err
}

// GetProjects returns all projects from the database.
func (s *ApiService) GetProjects() ([]models.Project, error) {
	projects := []models.Project{}
	err := s.db.Select(&projects, "SELECT * FROM projects")
	return projects, err
}

// GetProject returns a project from the database.
func (s *ApiService) GetProject(id string) (models.Project, error) {
	project := models.Project{}
	err := s.db.Get(&project, "SELECT * FROM projects WHERE id = ?", id)
	return project, err
}

// CreateProject creates a new project in the database.
func (s *ApiService) CreateProject(project models.Project) (int64, error) {
	result, err := s.db.Exec("INSERT INTO projects (name, owner_id, description, status, platform, created_at) VALUES (?, ?, ?, ?, ?, ?)", project.Name, 1, project.Description, "in_progress", project.Platform, time.Now())

	if err != nil {
		return 0, err
	}

	return result.LastInsertId()
}

// UpdateProject updates a project in the database.
func (s *ApiService) UpdateProject(project models.Project) (int64, error) {
	result, err := s.db.Exec("UPDATE projects SET name = ?, description = ?, status = ?, platform = ?, updated_at = ? WHERE id = ?", project.Name, project.Description, project.Status, project.Platform, time.Now(), project.ID)

	if err != nil {
		return 0, err
	}

	return result.RowsAffected()
}

// DeleteProject deletes a project from the database.
func (s *ApiService) DeleteProject(id string) (int64, error) {
	result, err := s.db.Exec("DELETE FROM projects WHERE id = ?", id)
	if err != nil {
		return 0, err
	}

	return result.RowsAffected()
}
